package com.g2.rpc.rpc.balance;


import com.g2.rpc.rpc.Invoker;
import com.g2.rpc.rpc.LoadBalance;

import java.net.URI;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

public class RoundLoadBalance implements LoadBalance {

    private AtomicInteger nextServerCyclicCounter = new AtomicInteger();

    @Override
    public Invoker select(Map<URI, Invoker> invokerMap) {
        while (true) {
            int current = nextServerCyclicCounter.get();
            int next = (current + 1) % invokerMap.size();
            if (nextServerCyclicCounter.compareAndSet(current, next)) {
                return invokerMap.values().toArray(new Invoker[]{})[next];
            }
        }
    }
}
